package com.china08.yxyapi.api.manage.stu.mystudy.huixue.studyrecord;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlan;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnow;
import com.china08.yxyapi.entity.mg.huixue.YxyHuixuePlanKnowTrainQues;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowTrainQuesRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanKnowTrainRepository;
import com.china08.yxyapi.repository.mg.huixue.YxyHuixuePlanRepository;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

/**
 * 学习记录 记录详情
 * 
 */
@CrossOrigin
@RestController
public class HuiXueStudyRecoredDetailController extends YxyApiBaseController {

    @Autowired
    private YxyHuixuePlanRepository yxyHuixuePlanRepository;
    @Autowired
    private YxyHuixuePlanKnowRepository yxyHuixuePlanKnowRepository;
    @Autowired
    private YxyHuixuePlanKnowTrainQuesRepository yxyHuixuePlanKnowTrainQuesRepository;
    @Autowired
    private YxyHuixuePlanKnowTrainRepository yxyHuixuePlanKnowTrainRepository;

    @Autowired
    private MongoTemplate mTemplate;
    @RequestMapping(value = "/api_yw/manage/stu/mystudy/huixue/studyrecored/recoreddetail/list", method = RequestMethod.POST)
    public RespModel precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel)
            throws ParseException {
        RespModel model = new RespModel();
        YxyHuixuePlan yxyHuixuePlan = yxyHuixuePlanRepository.findById(reqModel.planId);
        if (yxyHuixuePlan != null) {
            model.lastScoreType = yxyHuixuePlan.getLastScoreType(); // 上次考试分值（尺子的总长度）,
                                                                    // 100,120,150,180
            model.lastScore = yxyHuixuePlan.getLastScore(); // 初始分数
            model.expectScore = yxyHuixuePlan.getExpectScore();// 目前提分
            model.progress = yxyHuixuePlan.getProgress();// 目标完成度
            model.chiScore = model.expectScore * model.progress * 0.01 + model.lastScore; // 尺子的考试分数(目标提分*目标完成度+初始分数)
            model.mubiaoScore = model.lastScore + model.expectScore;// 目标分数
            model.currentScore = yxyHuixuePlan.getCurrentScore();// 实际分数
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            // 开始时间
            Integer beginDate = yxyHuixuePlan.getBeginDate();
            String beginDateString = null;
            Date beginDate2 = null;
            if (beginDate != null && beginDate != 0) {
                beginDateString = String.valueOf(beginDate);
                beginDateString = beginDateString.substring(0, 4) + "-" + beginDateString.substring(4, 6) + "-"
                        + beginDateString.substring(6);
                beginDate2 = sdf.parse(beginDateString);
            }
            // 结束时间
            Integer endDate = yxyHuixuePlan.getEndDate();
            String endDateString = null;
            Date endDate2 = null;
            if (endDate != null && endDate != 0) {
                endDateString = String.valueOf(endDate);
                endDateString = endDateString.substring(0, 4) + "-" + endDateString.substring(4, 6) + "-"
                        + endDateString.substring(6);
                endDate2 = sdf.parse(endDateString);
            }
            model.days = this.getIntervalDays(beginDate2, endDate2);// 学习计划用时
//            long knowCount = yxyHuixuePlanKnowRepository.countByPlanIdAndProgress(yxyHuixuePlan.getId(), (double) 100);// 已完成计划的知识点数量
            
            // 已完成计划的知识点数量(去除重复知识点)
            DBCollection collection = mTemplate.getCollection(mTemplate.getCollectionName(YxyHuixuePlanKnow.class));
            DBObject dbObject = new BasicDBObject("plan_id", yxyHuixuePlan.getId());
            dbObject.put("progress", (double) 100);
            @SuppressWarnings("rawtypes")
            List list = collection.distinct("pk_id", dbObject);
            long knowCount = list.size();
            
            
            
            
            Object[] obj = new Object[2];
            obj[0] = yxyHuixuePlan.getKnowCount();
            obj[1] = knowCount;
            model.knowDescription = obj;
            Object[] objects = new Object[4];
            if (model.progress == 100) {
                objects[0] = 1;// 已经完成时用微笑图示
                objects[1] = "在" + yxyHuixuePlan.getSemesterName() + "中的" + yxyHuixuePlan.getBookContentName();
                objects[2] = model.lastScore;
                objects[3] = model.mubiaoScore;
            } else if (model.progress < 100) {
                objects[0] = 0;// 未完成时用遗憾图示
                objects[1] = "在" + yxyHuixuePlan.getSemesterName() + "中的" + yxyHuixuePlan.getBookContentName();
                objects[2] = model.lastScore;
                objects[3] = model.mubiaoScore;
            }
            model.objs = objects;// 知识点统计下面判断的那句话
            model.charName = yxyHuixuePlan.getBookContentName();// 学习计划中选择的章
        } else {
            model.lastScoreType = 0; // 上次考试分值（尺子的总长度）, 100,120,150,180
            model.lastScore = 0d; // 初始分数
            model.expectScore = 0;// 目前提分
            model.progress = 0d;// 目标完成度
            model.currentScore = 0d;// 实际分数
            model.chiScore = 0d; // 尺子的考试分数(目标提分*目标完成度+初始分数)
            model.mubiaoScore = 0d;// 目标分数
            model.days = 0;// 学习计划用时
            Object[] obj = new Object[2];
            model.knowDescription = obj;
            Object[] objects = new Object[2];
            model.objs = objects;// 知识点统计下面判断的那句话
            model.charName = "";// 学习计划中选择的章
        }

        List<Object[]> objs = new ArrayList<Object[]>();
        if (StringUtils.isNotBlank(reqModel.planId)) {
            List<YxyHuixuePlanKnow> yxyHuixuePlanKnowTrainLst = yxyHuixuePlanKnowRepository
                    .findByPlanIdOrderByOrderNumAsc(reqModel.planId);// 通过计划id查出来总共有多少个章节
            if (yxyHuixuePlanKnowTrainLst != null && yxyHuixuePlanKnowTrainLst.size() > 0) {
                Map<String, List<YxyHuixuePlanKnow>> groupByYxyHuixuePlanKnowTrain = yxyHuixuePlanKnowTrainLst.stream()
                        .collect(Collectors.groupingBy(YxyHuixuePlanKnow::getBookContentsName));

                // 根据orderNum对分组后的集合进行排序
                Map<String, List<YxyHuixuePlanKnow>> groupByYxyHuixuePlanKnowTrain2 = new LinkedHashMap<>();
                groupByYxyHuixuePlanKnowTrain.entrySet().stream()
                        .sorted(new Comparator<Map.Entry<String, List<YxyHuixuePlanKnow>>>() {
                            @Override
                            public int compare(Entry<String, List<YxyHuixuePlanKnow>> o1,
                                    Entry<String, List<YxyHuixuePlanKnow>> o2) {
                                return o1.getValue().get(0).getOrderNum().compareTo(o2.getValue().get(0).getOrderNum()); // 升序
                            }
                        }).forEachOrdered(e -> groupByYxyHuixuePlanKnowTrain2.put(e.getKey(), e.getValue()));

                Object[] objects2 = null;
                List<CharpterModel> charpterModels = null;
                for (String key : groupByYxyHuixuePlanKnowTrain2.keySet()) {
                    CharpterModel charpterModel = null;
                    charpterModels = new ArrayList<CharpterModel>();
                    objects2 = new Object[2];
                    objects2[0] = key;
                    for (YxyHuixuePlanKnow yxyHuixuePlanKnow : groupByYxyHuixuePlanKnowTrain.get(key)) {
                        charpterModel = new CharpterModel();
                        charpterModel.knowName = yxyHuixuePlanKnow.getKnowName();
                        charpterModel.attention = yxyHuixuePlanKnow.getAttention();
                        charpterModel.progress = yxyHuixuePlanKnow.getProgress();
                        if (StringUtils.isNotBlank(reqModel.studentId)) {
                            charpterModel.countTrain = yxyHuixuePlanKnowTrainRepository
                                    .countByPlanIdAndKnowId(reqModel.planId, yxyHuixuePlanKnow.getKnowId());
                        } else {
                            charpterModel.countTrain = 0l;
                        }
                        List<YxyHuixuePlanKnowTrainQues> yxyHuixuePlanKnowTrainQuesLst = yxyHuixuePlanKnowTrainQuesRepository
                                .findDistinctYxyHuixuePlanKnowTrainQuesByStudentIdAndPlanIdAndKnowIdAndPassed(
                                        reqModel.studentId, reqModel.planId, yxyHuixuePlanKnow.getKnowId(), 0);
                        Set<String> questIdSet = new HashSet<String>();
                        for (YxyHuixuePlanKnowTrainQues yxyHuixuePlanKnowTrainQues : yxyHuixuePlanKnowTrainQuesLst) {
                            questIdSet.add(yxyHuixuePlanKnowTrainQues.getQuesId());
                        }
                        charpterModel.quesCount = yxyHuixuePlanKnowTrainQuesLst.size();// 错题总数
                        charpterModel.knowId = yxyHuixuePlanKnow.getKnowId();
                        charpterModel.studentId = reqModel.studentId;
                        charpterModel.planId = reqModel.planId;
                        charpterModels.add(charpterModel);
                    }
                    objects2[1] = charpterModels;
                    objs.add(objects2);
                }
            }

        }
        model.studObjects = objs;
        return model;

    }

    protected static class RespModel extends YxyApiRespModel {
        // 上次考试分值
        public Integer lastScoreType;// 上次考试成绩分值（尺子的总长度）, 100,120,150,180
        // 初始分数
        public Double lastScore;// 上次考试分数, 小数点后一位
        // 目前提分
        public Integer expectScore;// 预期提高分数, 5, 10, 15, 20
        // 实际提分
        public Double currentScore;
        // 目标分数
        public Double mubiaoScore;
        // 尺子的考试分数(目标提分*目标完成度+初始分数)
        public Double chiScore;
        // 学习计划用时
        public Integer days;
        // 知识点统计长度为2，第一个参数是（本次计划共涉及多少个知识点），第二个参数是（已完成计划的知识点有多少个）
        // 在前端页面拼接时格式："本次计划共涉及"+knowDescription[0]+"个知识点
        // 已完成计划的知识点有"+knowDescription[1]+"个"
        public Object[] knowDescription;
        // 完成度
        public Double progress;
        // 知识点统计下面判断的那句话
        // 长度为4，第一个参数是判断图片是遗憾还是微笑（0，代表微笑，1代表遗憾），第二个参数是（在八年级上册中的第十一章《三角形》），
        // 第三个参数是指将分数从多少分，第四个参数是指提高到多少分
        // 在前端页面拼接时格式：if(objs[0] == 0)时图片为笑脸，格式:objs[1]
        // +"将分数从"+objs[2]+"分提高到"+objs[3]+"分的计划已经结束！已完成计划
        // if(objs[0] == 1)时图片为遗憾，格式:objs[1]
        // +"将分数从"+objs[2]+"分提高到"+objs[3]+"分的计划已经结束！未完成计划
        public Object[] objs;
        // 学习计划中选择的章
        public String charName;
        // 学习计划中章节下面所对应的所有小节及知识点情况
        public List<Object[]> studObjects;
    }

    protected class CharpterModel {
        // 知识点名称
        public String knowName;
        // 关注等级
        public Integer attention;
        // 知识点完成度
        public Double progress;
        // 训练次数
        public Long countTrain;
        // 错题总数
        public Integer quesCount;
        // 知识点id
        public String knowId;
        // studentId
        public String studentId;
        // 计划id
        public String planId;
    }

    protected static class ReqModel extends YxyApiReqModel {
        // 计划id
        public String planId;
        // 学生id
        public String studentId;
    }

    private Integer getIntervalDays(Date fDate, Date oDate) {

        if (null == fDate || null == oDate) {

        return -1;

        }

        long intervalMilli = oDate.getTime() - fDate.getTime();

        return (int) (intervalMilli / (24 * 60 * 60 * 1000));

    }
}
